<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 作品作品配置类
 */
class CodeGuideProductionController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\CodeGuideProduction();
        $this->validate = new  \App\Validate\CodeGuideProductionValidate();
    }

    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param exhibition_id string 作品id
     * @param type_id string 类型id
     * @param keywords string 搜索关键词
     * @param start_time datetime 创建开始时间   数据格式 年月日时分秒
     * @param end_time datetime 创建结束时间
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $exhibition_id = $this->request->exhibition_id;
        $keywords = $this->request->keywords;
        $type_id = $this->request->type_id;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;

        $res = $this->model->lists(null, $keywords, $exhibition_id, $type_id, $start_time, $end_time, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        //获取作品数量
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['content'] =  strip_tags($val['content']);
            $res['data'][$key]['exhibition_name'] = !empty($val['con_exhibition']['name']) ?  $val['con_exhibition']['name'] : '';
            $res['data'][$key]['type_name'] = !empty($val['con_type']['type_name']) ?  $val['con_type']['type_name'] : '';
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            $img_arr = [];
            if ($val['img']) {
                $img = explode("|", $val['img']);
                $thumb_img = explode("|", $val['thumb_img']);

                foreach ($img as $k => $v) {
                    $img_arr[$k]['img'] = $v;
                    $img_arr[$k]['thumb_img'] = $thumb_img[$k];
                }
            }
            $res['data'][$key]['img_arr'] = $img_arr;

            unset($res['data'][$key]['con_exhibition'], $res['data'][$key]['con_type'], $res['data'][$key]['img'], $res['data'][$key]['thumb_img']);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 作品id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;

        $res = $this->model->detail($id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res = $res->toArray();
        $res['exhibition_name'] = !empty($res['con_exhibition']['name']) ?  $res['con_exhibition']['name'] : '';
        $res['type_name'] = !empty($res['con_type']['type_name']) ?  $res['con_type']['type_name'] : '';

        $img_arr = [];
        if ($res['img']) {
            $img = explode("|", $res['img']);
            $thumb_img = explode("|", $res['thumb_img']);
            foreach ($img as $key => $val) {
                $img_arr[$key]['img'] = $val;
                $img_arr[$key]['thumb_img'] = $thumb_img[$key];
            }
        }
        $res['img_arr'] = $img_arr;
        unset($res['con_exhibition'], $res['con_type'], $res['img'], $res['thumb_img']);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 新增
     * @param name string 作品名
     * @param exhibition_id string 展览id
     * @param type_id string 类型id
     * @param img string 图片,多张用 | 拼接   图片、文字、音频、视频，最少存在一种
     * @param content string 作品正文内容
     * @param voice string 作品音频地址，可以用内容直接转换成语音
     * @param voice_name string 作品音频名称
     * @param video string 作品视频地址
     * @param video_name string 作品视频名称
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (empty($this->request->img) && empty($this->request->content) && empty($this->request->voice) && empty($this->request->video)) {
            return $this->returnApi(202, "请填写导游信息");
        }
        $voice = $this->request->voice;
        $video = $this->request->video;
        $is_exists = $this->model->nameIsExists($this->request->name, 'name');
        if ($is_exists) {
            return $this->returnApi(202, "该导游名称已存在");
        }


        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('code_guide_production');
        if ($qr_code === false) {
            Log::error("扫码导游作品二维码生成失败,请手动生成");
            return $this->returnApi(201, "添加失败，请重新添加");
        }
        //生成二维码
        $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pCodeNav/detail/index?from=code_guide_production&token=' . $qr_code;
        $qr_url = $qrCodeObj->setQr($qr_data, true, 300, 1, [0, 0, 0]);

        // 启动事务
        DB::beginTransaction();
        try {
            $img_arr = explode('|', $this->request->img);
            $thumb_img = '';
            foreach ($img_arr as $key => $val) {
                $thumb_img .= '|' . str_replace('.', '_thumb.', $val);
            }
            $thumb_img = trim($thumb_img, '|');

            //如果是临时图片，移动到指定位置
            if ($voice  && strpos($voice, 'temp_audio') !== false) {
                $move_file = $this->moveUploadedFile($voice,  'code_guide_production_audio');
                if (!$move_file) {
                    throw new \Exception('音频保存失败');
                }
                $voice = $move_file;
            }

            //如果是临时图片，移动到指定位置
            if ($video  && strpos($video, 'temp_video') !== false) {
                $move_file = $this->moveUploadedFile($video,  'code_guide_production_audio');
                if (!$move_file) {
                    throw new \Exception('视频保存失败');
                }
                $video = $move_file;
            }

            $data = [
                'name' => $this->request->name,
                'exhibition_id' => $this->request->exhibition_id,
                'type_id' => $this->request->type_id,
                'img' => $this->request->img,
                'thumb_img' => $thumb_img,
                'content' => $this->request->content,
                'voice' => $voice,
                'voice_name' => $this->request->voice_name,
                'video' => $video,
                'video_name' => $this->request->video_name,
                'qr_code' => $qr_code,
                'qr_url' => $qr_url,
                'manage_id' => $this->request->manage_id,
            ];
            $this->model->add($data);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "添加成功", true);
        } catch (\Exception $e) {
            //   var_dump($e->getMessage());exit;
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "添加失败" . $e->getMessage());
        }
    }



    /**
     * 编辑
     * @param id int 作品id
     * @param name string 作品名
     * @param exhibition_id string 展览id
     * @param type_id string 类型id
     * @param img string 图片,多张用 | 拼接   图片、文字、音频、视频，最少存在一种
     * @param content string 作品正文内容
     * @param voice string 作品音频地址，可以用内容直接转换成语音
     * @param voice_name string 作品音频名称
     * @param video string 作品视频地址
     * @param video_name string 作品视频名称
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (empty($this->request->img) && empty($this->request->content) && empty($this->request->voice) && empty($this->request->video)) {
            return $this->returnApi(202, "请填写导游信息");
        }

        $is_exists = $this->model->nameIsExists($this->request->name, 'name', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该导游名称已存在");
        }

        $id = $this->request->id;
        $voice = $this->request->voice;
        $video = $this->request->video;
        $res = $this->model->detail($id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        $old_img = $res->img;
        $old_voice = $res->voice;
        $old_video = $res->video;

        // 启动事务
        DB::beginTransaction();
        try {

            $img_arr = explode('|', $this->request->img);
            $thumb_img = '';
            foreach ($img_arr as $key => $val) {
                $thumb_img .= '|' . str_replace('.', '_thumb.', $val);
            }
            $thumb_img = trim($thumb_img, '|');

            //如果是临时图片，移动到指定位置
            if ($voice  && strpos($voice, 'temp_audio') !== false) {
                $move_file = $this->moveUploadedFile($voice,  'code_guide_production_audio');
                if (!$move_file) {
                    throw new \Exception('音频保存失败');
                }
                $voice = $move_file;
            }

            //如果是临时图片，移动到指定位置
            if ($video  && strpos($video, 'temp_video') !== false) {
                $move_file = $this->moveUploadedFile($video,  'code_guide_production_audio');
                if (!$move_file) {
                    throw new \Exception('视频保存失败');
                }
                $video = $move_file;
            }

            $data = [
                'id' => $this->request->id,
                'name' => $this->request->name,
                'exhibition_id' => $this->request->exhibition_id,
                'type_id' => $this->request->type_id,
                'img' => $this->request->img,
                'thumb_img' => $thumb_img,
                'content' => $this->request->content,
                'voice' => $voice,
                'voice_name' => $this->request->voice_name,
                'video' => $video,
                'video_name' => $this->request->video_name,
            ];

            if (empty($res['qr_url'])) {
                //生成二维码
                $qrCodeObj = new QrCodeController();
                if (empty($res['qr_code'])) {
                    $qr_code = $qrCodeObj->getQrCode('code_guide_production');
                    if ($qr_code === false) {
                        Log::error("扫码导游作品二维码生成失败,请手动生成");
                        throw new Exception("二维码生成失败");
                    }
                } else {
                    $qr_code = $res['qr_code'];
                }
                //生成二维码
                $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pCodeNav/detail/index?from=code_guide_production&token=' . $qr_code;
                $qr_url = $qrCodeObj->setQr($qr_data, true, 300, 1, [0, 0, 0]);
                $data['qr_url'] = $qr_url;
                $data['qr_code'] = $qr_code;
            }

            $this->model->change($data);

            //删除旧资源
            $old_img = explode("|", $old_img);
            foreach ($old_img as $key => $val) {
                if (in_array($val, $img_arr)) {
                    unset($old_img[$key]);
                }
            }
            if ($old_img) {
                $old_img = explode('|', join('|', $old_img)); //重置一次健名
                $this->deleteFile($old_img);
            }
            //删除旧资源
            if ($old_voice != $this->request->voice) {
                $this->deleteFile($old_voice);
            }
            //删除旧资源
            if ($old_video != $this->request->video) {
                $this->deleteFile($old_video);
            }
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 作品id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }
}
